invertshares_FE <- function(theta2, x_char, expmeanval, tol_inner, share, v, Y, oo, sharesum, marketForProducts, marketStarts, marketEnds, K, K_A, nD, T, nn, countries) {

ii<-0
norm_max<-1
expmeanval0<-expmeanval
expmeanval0 <- as.matrix(expmeanval0)

expmu = matrix(0,nrow(x_char),ncol(v))

for (t in 1:T) { 
theta2_mat = rbind(as.matrix(theta2[1:(K_A+1)]), theta2[length(theta2)-nD+1]*as.matrix(theta2[(nD*(K_A+1)+1):(length(theta2)-nD)]))
expmu[marketStarts[t,1]:marketEnds[t,1],] = exp(x_char[marketStarts[t,1]:marketEnds[t,1],]%*%diag(as.numeric(theta2_mat))%*%v[1:(K+1),,t] + x_char[marketStarts[t,1]:marketEnds[t,1],]%*% rbind(matrix(0,K_A+1,1), as.matrix(theta2[(nD*(K_A+1)+1):(length(theta2)-nD)]))%*%matrix(1,1,nn))   
for (dd in 2:nD) {
theta2_mat = rbind(as.matrix(theta2[((dd-1)*(K_A+1)+1):(dd*(K_A+1))]), theta2[length(theta2)-nD+dd]*as.matrix(theta2[(nD*(K_A+1)+1):(length(theta2)-nD)]))   
expmu[marketStarts[t,1]:marketEnds[t,1],] = expmu[marketStarts[t,1]:marketEnds[t,1],] * exp(x_char[marketStarts[t,1]:marketEnds[t,1],]%*%diag(as.numeric(theta2_mat))%*%v[((dd-1)*(K+1)+1):(dd*(K+1)),,t]) 
}
}


expmeanval0 = invert_cpp(as.matrix(expmeanval), as.matrix(share), expmu, oo, sharesum, marketForProducts-1)

if (max(is.nan(expmeanval0))<1) {
expmeanval = expmeanval0
}

delta<-log(expmeanval)  

return(delta)

}


